<?php

namespace app\admin\controller;

use think\Controller;
use think\Db;
use think\Request;

class Con1 extends Con4
{
    public function index()
    {
        $sql = "SELECT * FROM `lamp_user`";

        $list = Db::query($sql);
        return view('admin@con1/tables', ['list' => $list]);
    }

    public function func1()
    {
        return view('admin@con1/func1');
    }

    public function func2(Request $request)
    {
       $p = $request->post();

       $data = [
            'username' => $p['username'],
            'name' => $p['name'],
            'userpass' => md5($p['userpass']),
            'sex' => $p['sex'],
       ];

        $result = Db::table('lamp_user')->data($data)->insert();

        if ($result >0 ){
            return $this->success('新增成功',url('admin/Con1/index'));
        }else{
            return $this->success('新增失败');
        }
    }

    public function addrole($id)
    {

        $uid[0]= ['id'=>$id];

        $sql = "SELECT * FROM `lamp_role`";
        $role = Db::query($sql);
        $data = Db::table('lamp_user_role')->field('rid')->where('uid = '.$id)->select();
        foreach ($role as $k => $v) {
            $role[$k]['rid'] = $id;
            $role[$k]['check'] = null;
            foreach ($data as $y) {
                if ($v['id'] == $y['rid']) {
                    $role[$k]['check'] = 'checked';
                }
            }
        }

        $uid[0] = ['uid' => $id];
        // var_dump($uid);
        return view('admin@con1/func2',[
            'role' => $role,
            'uid' => $uid
            ]);
    }

    public function doaddrole(Request $request)
    {
        $p = $request->post();
        $uid = $p['uid'];

        Db::table('lamp_user_role')->where('uid = '.$uid)->delete();

        $a = ['uid' => $p['uid']];

        if ($p !== $a) {
            foreach ($p['rid'] as $v) {
                $data = [
                    'uid' => $p['uid'],
                    'rid' => $v
                ];
                $result = Db::table('lamp_user_role')->insert($data);
            }
        }else{
            return $this->success('新增成功',url('admin/Con1/index'));
        }


        if ($result >0 ){
            return $this->success('新增成功',url('admin/Con1/index'));
        }else{
            return $this->success('新增失败');
        }
    }


}